/*
 * Copyright (C) 2009 AnK Team
 *	 Andrey Korolev
 *	 Anna Krel
 *	 Anna Kapanina
 *	 
 *	 http://code.google.com/p/ankfood/	
 *    
     
 *    Licensed under the GNU General Public License, Version 2.0 (the "License");
 *
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *         http://www.gnu.org/licenses/gpl-2.0.html

 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,

 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

package org.ank.food;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;

public class ProfileActivity extends Activity {
	
	public static final int WEIGHT_UNIT_LB = 1;
	public static final int WEIGHT_UNIT_KG = 0;
	
	public static final int HEIGHT_UNIT_INCH = 1;
	public static final int HEIGHT_UNIT_CM = 0;
	public static final int PROFILE_MODE_CREATE = 0;
	public static final String INTENT_EXTRA_NAME = "profile intent";
	
	private EditText nameView, ageView, weightView, heightView;
	private Spinner	physActSpinner, weightUnitSpinner, heightUnitSpinner;
	private Button saveButton;
	private RadioGroup genderGroup;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.profile_activity);
        
        nameView = (EditText)findViewById(R.id.profile_name_value);
        ageView = (EditText)findViewById(R.id.profile_age_value);
        weightView = (EditText)findViewById(R.id.profile_weight_value);
        heightView = (EditText)findViewById(R.id.profile_height_value);
        physActSpinner = (Spinner)findViewById(R.id.profile_phys_act_spinner);
        weightUnitSpinner = (Spinner)findViewById(R.id.profile_weight_unit);
        heightUnitSpinner = (Spinner)findViewById(R.id.profile_height_unit);
        saveButton = (Button)findViewById(R.id.profile_save_button);
        genderGroup = (RadioGroup)findViewById(R.id.profile_gender_radiogroup);
   
        if (ProfileManager.getInstance(getApplicationContext()).noProfilesExist()){
        	ProfileManager.getInstance(getApplicationContext()).
        			setProfileMode(ProfileManager.PROFILE_MODE_CREATE);
        	Log.v("pa", "profile mode create");
        }
        else{
        	ProfileManager.getInstance(getApplicationContext()).
					setProfileMode(ProfileManager.PROFILE_MODE_EDIT);
        	Log.v("pa", "profile mode edit");
        }
        
        ArrayAdapter<CharSequence> physActAdapter = ArrayAdapter.createFromResource(
                getApplicationContext(), R.array.phys_act_strings, android.R.layout.simple_spinner_item);
        physActAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        physActSpinner.setAdapter(physActAdapter);
        
        ArrayAdapter<CharSequence> weightUnitAdapter = ArrayAdapter.createFromResource(
                getApplicationContext(), R.array.weight_unit_strings, android.R.layout.simple_spinner_item);
        weightUnitAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        weightUnitSpinner.setAdapter(weightUnitAdapter);
        
        ArrayAdapter<CharSequence> heightUnitAdapter = ArrayAdapter.createFromResource(
                getApplicationContext(), R.array.height_unit_strings, android.R.layout.simple_spinner_item);
        heightUnitAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        heightUnitSpinner.setAdapter(heightUnitAdapter);
        
        
        if (ProfileManager.getInstance(getApplicationContext()).getProfileMode() == 
				ProfileManager.PROFILE_MODE_EDIT){
        	setTitle(getTitle()+" - "+ProfileManager.getInstance(getApplicationContext()).
        			getCurrentProfileName());
        	nameView.setText(ProfileManager.getInstance(getApplicationContext()).
        			getCurrentProfileName());
        	switch (ProfileManager.getInstance(getApplicationContext()).getCurrentProfileGender()){
        		case ProfileManager.MALE :
        			genderGroup.check(R.id.profile_gender_male_button);
        			break;
        		case ProfileManager.FEMALE :
        			genderGroup.check(R.id.profile_gender_female_button);
        			break;
        	}
        	ageView.setText(String.valueOf(ProfileManager.getInstance(getApplicationContext())
        			.getCurrentProfileAge()));
        	weightView.setText(	String.valueOf( ProfileManager.getInstance(getApplicationContext())
        				.getCurrentProfileWeight() ));
        	heightView.setText(	String.valueOf(
        				ProfileManager.getInstance(getApplicationContext())
        				.getCurrentProfileHeight() ) );
        	weightUnitSpinner.setSelection(ProfileManager.getInstance(getApplicationContext())
        			.getCurrentProfileWeightUnit());
        	heightUnitSpinner.setSelection(ProfileManager.getInstance(getApplicationContext())
        			.getCurrentProfileHeightUnit());
        	physActSpinner.setSelection(ProfileManager.getInstance(getApplicationContext())
        			.getCurrentProfilePhysAct());
        }
        
        saveButton.setOnClickListener(new Button.OnClickListener(){
			public void onClick(View v){
				if (checkAndSaveInfo()){
					Intent intent = new Intent(getApplicationContext(), MenuActivity.class);
					startActivity(intent);
				}
			}
        });
    }
    private boolean checkAndSaveInfo(){
    	//check name presence and spelling
		String name = nameView.getText().toString();
		if ( name.equals("") ){
			Toast.makeText(getApplicationContext(), R.string.specify_name,
					Toast.LENGTH_SHORT).show();
			return false;
		}
		if ( name.contains("\"") || name.contains("_") || name.contains("%") ){
			Toast.makeText(getApplicationContext(), R.string.dont_use_symbols_in_name,
					Toast.LENGTH_LONG).show();
			return false;
		}
		if ( ProfileManager.getInstance(getApplicationContext()).profileNameExists(name) && 
				(ProfileManager.getInstance(getApplicationContext()).getProfileMode() ==	ProfileManager.PROFILE_MODE_CREATE) ){
			Toast.makeText(getApplicationContext(), R.string.profile_exists,
					Toast.LENGTH_LONG).show();
			return false;
		}
		
		//check that gender is specified
		if (genderGroup.getCheckedRadioButtonId() == -1){
			Toast.makeText(getApplicationContext(), R.string.specify_gender,
					Toast.LENGTH_SHORT).show();
			return false;
		}
		
		//check that age is specified
		String age = ageView.getText().toString();
		if ( age.equals("") || Integer.parseInt(age) < 3){
			Toast.makeText(getApplicationContext(), R.string.specify_age,
					Toast.LENGTH_SHORT).show();
			return false;
		}
		
		//check that weight is specified
		String weightString = weightView.getText().toString();
		if ( weightString.equals("") ){
			Toast.makeText(getApplicationContext(), R.string.specify_weight,
					Toast.LENGTH_SHORT).show();
			return false;
		}
		
		//check that height is specified
		String heightString = heightView.getText().toString();
		if ( heightString.equals("") ){
			Toast.makeText(getApplicationContext(), R.string.specify_height,
					Toast.LENGTH_SHORT).show();
			return false;
		}
		
		int gender;
		if(genderGroup.getCheckedRadioButtonId() == R.id.profile_gender_male_button)
			gender = ProfileManager.MALE;
		else
			gender = ProfileManager.FEMALE;
		
		//save profile
		ProfileManager.getInstance(getApplicationContext()).
			saveNewOrUpdateProfile(
					name, 
					gender, 
					Integer.parseInt(age), 
					Integer.parseInt(weightString), 
					Integer.parseInt(heightString), 
					physActSpinner.getSelectedItemPosition(),
					weightUnitSpinner.getSelectedItemPosition(),
					heightUnitSpinner.getSelectedItemPosition()
			);
		
		Toast.makeText(getApplicationContext(), R.string.profile_saved,
				Toast.LENGTH_SHORT).show();
		return true;
    }
    
    public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) 
			if(!checkAndSaveInfo())
				return true;
		
		return super.onKeyDown(keyCode, event);
	}
}